import 'package:azring/gen/assets.gen.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/widgets/area_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'shipping_address_state.dart';

class ShippingAddressLogic extends GetxController {
  final state = ShippingAddressState();
  final api = DefaultApi();
  List<Map<String, dynamic>> areaData = [];
  bool isLoadingArea = false;

  @override
  void onInit() {
    super.onInit();
    loadAddresses();
  }

  /// 加载省市区数据
  Future<bool> loadAreaData() async {
    if (isLoadingArea) return false;
    if (areaData.isNotEmpty) return true;
    
    isLoadingArea = true;
    try {
      final data = await api.queryProvinceGet();
      
      if (data.isNotEmpty) {
        areaData = data;
        print('成功加载省市区数据，共 ${areaData.length} 个省份');
        return true;
      }
      
      print('省市区数据为空');
      return false;
    } catch (e) {
      print('加载省市区数据失败: $e');
      return false;
    } finally {
      isLoadingArea = false;
    }
  }

  /// 粘贴并识别地址
  Future<void> _pasteAndRecognize(
    TextEditingController nameController,
    TextEditingController phoneController,
    TextEditingController detailedAddressController,
    RxString selectedProvince,
    RxString selectedCity,
    RxString selectedDistrict,
  ) async {
    try {
      // 从剪贴板读取内容
      final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
      final text = clipboardData?.text?.trim();
      
      if (text == null || text.isEmpty) {
       Toast.show( '剪贴板为空');
        return;
      }
      
      print('剪贴板内容: $text');
      
      // 解析地址信息
      final addressInfo = _parseAddress(text);
      
      if (addressInfo.isEmpty) {
        Toast.show( '无法识别地址信息，请手动填写');
        return;
      }
      
      // 填充表单
      if (addressInfo['name'] != null) {
        nameController.text = addressInfo['name']!;
      }
      if (addressInfo['phone'] != null) {
        phoneController.text = addressInfo['phone']!;
      }
      if (addressInfo['province'] != null) {
        selectedProvince.value = addressInfo['province']!;
      }
      if (addressInfo['city'] != null) {
        selectedCity.value = addressInfo['city']!;
      }
      if (addressInfo['district'] != null) {
        selectedDistrict.value = addressInfo['district']!;
      }
      if (addressInfo['detailedAddress'] != null) {
        detailedAddressController.text = addressInfo['detailedAddress']!;
      }
      
      Toast.show( '地址识别成功');
    } catch (e) {
      print('粘贴识别失败: $e');
      Toast.show( '识别失败，请手动填写');
    }
  }

  /// 解析地址文本
  Map<String, String> _parseAddress(String text) {
    final result = <String, String>{};
    
    // 提取手机号（11位数字）
    final phoneRegex = RegExp(r'1[3-9]\d{9}');
    final phoneMatch = phoneRegex.firstMatch(text);
    if (phoneMatch != null) {
      result['phone'] = phoneMatch.group(0)!;
    }
    
    // 提取姓名（通常在开头，2-4个汉字）
    final nameRegex = RegExp(r'^[\u4e00-\u9fa5]{2,4}');
    final nameMatch = nameRegex.firstMatch(text);
    if (nameMatch != null) {
      result['name'] = nameMatch.group(0)!;
    }
    
    // 提取省市区
    // 常见省份关键词
    final provinces = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江',
      '上海', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
      '广东', '广西', '海南', '重庆', '四川', '贵州', '云南', '西藏', '陕西', '甘肃',
      '青海', '宁夏', '新疆'];
    
    for (final province in provinces) {
      if (text.contains(province)) {
        // 处理直辖市
        if (['北京', '天津', '上海', '重庆'].contains(province)) {
          result['province'] = '${province}市';
        } else if (province == '内蒙古') {
          result['province'] = '内蒙古自治区';
        } else if (province == '广西') {
          result['province'] = '广西壮族自治区';
        } else if (province == '西藏') {
          result['province'] = '西藏自治区';
        } else if (province == '宁夏') {
          result['province'] = '宁夏回族自治区';
        } else if (province == '新疆') {
          result['province'] = '新疆维吾尔自治区';
        } else {
          result['province'] = '${province}省';
        }
        break;
      }
    }
    
    // 提取市（XX市）
    final cityRegex = RegExp(r'[\u4e00-\u9fa5]{2,}市');
    final cityMatches = cityRegex.allMatches(text);
    if (cityMatches.isNotEmpty) {
      // 取第一个市（通常是地级市）
      result['city'] = cityMatches.first.group(0)!;
    }
    
    // 提取区/县（XX区、XX县）
    final districtRegex = RegExp(r'[\u4e00-\u9fa5]{2,}[区县]');
    final districtMatch = districtRegex.firstMatch(text);
    if (districtMatch != null) {
      result['district'] = districtMatch.group(0)!;
    }
    
    // 提取详细地址（去掉姓名、电话、省市区后的剩余部分）
    String detailedAddress = text;
    if (result['name'] != null) {
      detailedAddress = detailedAddress.replaceFirst(result['name']!, '');
    }
    if (result['phone'] != null) {
      detailedAddress = detailedAddress.replaceFirst(result['phone']!, '');
    }
    if (result['province'] != null) {
      detailedAddress = detailedAddress.replaceFirst(result['province']!, '');
    }
    if (result['city'] != null) {
      detailedAddress = detailedAddress.replaceFirst(result['city']!, '');
    }
    if (result['district'] != null) {
      detailedAddress = detailedAddress.replaceFirst(result['district']!, '');
    }
    
    // 清理详细地址（去掉空格、换行等）
    detailedAddress = detailedAddress.trim().replaceAll(RegExp(r'\s+'), '');
    if (detailedAddress.isNotEmpty) {
      result['detailedAddress'] = detailedAddress;
    }
    
    return result;
  }

  /// 加载地址列表
  Future<void> loadAddresses() async {
    try {
      state.isLoading.value = true;
      final response = await api.queryShippingAddressListGet<Map<String, dynamic>>();
      
      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        state.addressList.value = data.map((item) {
          final isDefaultValue = item['isDefault'];
          final isDefault = isDefaultValue == 1 ;
          
          return {
            'id': item['id'],
            'name': item['recipientName'],
            'phone': item['recipientPhone'],
            'isDefault': isDefault,
            'address': '${item['province']}${item['city']}${item['district']}${item['detailedAddress']}',
            'province': item['province'],
            'city': item['city'],
            'district': item['district'],
            'detailedAddress': item['detailedAddress'],
          };
        }).toList();
      }
    } catch (e) {
      Toast.show( '加载地址列表失败');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 添加新地址
  void addNewAddress() {
    _showAddressDialog();
  }

  /// 编辑地址
  void editAddress(Map<String, dynamic> address) {
    _showAddressDialog(address: address);
  }

  /// 删除地址
  Future<void> deleteAddress(int id) async {
    try {
      final response = await api.deleteShippingAddressDel<Map<String, dynamic>>(
        ids: id.toString(),
      );
      
      if (response != null && response['code'] == 200) {
        Toast.show('删除成功');
        loadAddresses();
      }
    } catch (e) {
      Toast.show( '删除失败');
    }
  }

  /// 保存地址
  Future<void> saveAddress({
    int? id,
    required String name,
    required String phone,
    required String province,
    required String city,
    required String district,
    required String detailedAddress,
    bool isDefault = false,
  }) async {
    try {
      final isDefaultStr = isDefault ? '1' : '0';
      
      if (id != null) {
        // 编辑地址
        final response = await api.updateShippingAddressPut<Map<String, dynamic>>(
          id: id,
          recipientName: name,
          recipientPhone: phone,
          province: province,
          city: city,
          district: district,
          detailedAddress: detailedAddress,
          isDefault: isDefaultStr,
        );
        
        if (response != null && response['code'] == 200) {
          Get.back();
          Toast.show('地址修改成功');
          loadAddresses();
        }
      } else {
        // 新增地址
        final response = await api.addShippingAddressPost<Map<String, dynamic>>(
          recipientName: name,
          recipientPhone: phone,
          province: province,
          city: city,
          district: district,
          detailedAddress: detailedAddress,
          isDefault: isDefaultStr,
        );
        
        if (response != null && response['code'] == 200) {
          Get.back();
          Toast.show( '地址添加成功');
          loadAddresses();
        }
      }
    } catch (e) {
      Toast.show( '保存失败');
    }
  }

  /// 显示地址编辑弹窗
  void _showAddressDialog({Map<String, dynamic>? address}) {
    final nameController = TextEditingController(text: address?['name'] ?? '');
    final phoneController = TextEditingController(text: address?['phone'] ?? '');
    final detailedAddressController = TextEditingController(text: address?['detailedAddress'] ?? '');
    
    // 地区选择
    final selectedProvince = RxString(address?['province'] ?? '');
    final selectedCity = RxString(address?['city'] ?? '');
    final selectedDistrict = RxString(address?['district'] ?? '');
    
    // 是否设为默认地址
    final isDefault = RxBool(address?['isDefault'] ?? false);

    Get.bottomSheet(
      Container(
        decoration: BoxDecoration(
          color: const Color(0xFF282725),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(top:36.h,left: 26.w,right: 26.w,bottom:43.h ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                
                // 标题
                Text(
                  address == null ? '添加新地址' : '编辑地址',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 27.h),
                // 粘贴识别区域
                Container(
                  height: 141.h,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: const Color(0xFF282725),
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(
                      color: const Color(0xFF3A3A3A),
                      width: 1,
                    ),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height:33.h),
                      GestureDetector(
                        onTap: () => _pasteAndRecognize(
                          nameController,
                          phoneController,
                          detailedAddressController,
                          selectedProvince,
                          selectedCity,
                          selectedDistrict,
                        ),
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 6.h),
                          decoration: BoxDecoration(
                            color: const Color(0xFF353535),
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Text(
                            '粘贴并识别',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: const Color(0xFFF67F41),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 11.h),
                      Text(
                        '复制地址后点此按钮，将自动填充以下信息',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Color(0xff979797),
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 28.h),
                // 收货人
                _buildInputField('收货人', '输入收货人姓名', nameController),
                // 联系电话
                _buildInputField('联系电话', '输入联系电话', phoneController),
                // 省市区
                Obx(() => _buildSelectField(
                  '省市区', 
                  selectedProvince.value.isEmpty 
                    ? '选择地区' 
                    : '${selectedProvince.value}${selectedCity.value}${selectedDistrict.value}',
                  onTap: () async {
                    // 显示加载提示
                    if (areaData.isEmpty) {
                      Get.dialog(
                        const Center(
                          child: CircularProgressIndicator(
                            color: Color(0xFFF67F41),
                          ),
                        ),
                        barrierDismissible: false,
                      );
                      
                      final success = await loadAreaData();
                      Get.back(); // 关闭加载提示
                      
                      if (!success) {
                        Toast.show( '地区数据加载失败，请稍后重试');
                        return;
                      }
                    }
                    
                    Get.bottomSheet(
                      AreaPicker(
                        initialProvince: selectedProvince.value,
                        initialCity: selectedCity.value,
                        initialDistrict: selectedDistrict.value,
                        areaData: areaData,
                        onConfirm: (province, city, district) {
                          selectedProvince.value = province;
                          selectedCity.value = city;
                          selectedDistrict.value = district;
                        },
                      ),
                      isScrollControlled: true,
                    );
                  },
                )),
                // 详细地址
                _buildInputField('详细地址', '请输入详细地址', detailedAddressController, showLocationIcon: true),
                // 设为默认地址
                Obx(() => GestureDetector(
                  onTap: () => isDefault.value = !isDefault.value,
                  child: Container(
                    padding: EdgeInsets.only(bottom: 40.h),
                    child: Row(
                      children: [
                        SizedBox(
                          width: 80.w,
                          child: Text(
                            '设为默认',
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w500,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        const Spacer(),
                        Container(
                          width: 20.w,
                          height: 20.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: isDefault.value 
                                ? const Color(0xFFF67F41) 
                                : const Color(0xFF3A3A3A),
                              width: 2,
                            ),
                            color: isDefault.value 
                              ? const Color(0xFFF67F41) 
                              : Colors.transparent,
                          ),
                          child: isDefault.value
                            ? Icon(
                                Icons.check,
                                size: 14.sp,
                                color: Colors.white,
                              )
                            : null,
                        ),
                      ],
                    ),
                  ),
                )),
                SizedBox(height: 30.h),
                // 保存按钮
                GestureDetector(
                  onTap: () {
                    // 验证输入
                    if (nameController.text.isEmpty) {
                      Toast.show( '请输入收货人姓名');
                      return;
                    }
                    if (phoneController.text.isEmpty) {
                      Toast.show('请输入联系电话');
                      return;
                    }
                    if (selectedProvince.value.isEmpty) {
                      Toast.show( '请选择省市区');
                      return;
                    }
                    if (detailedAddressController.text.isEmpty) {
                      Toast.show( '请输入详细地址');
                      return;
                    }
                    
                    // 保存地址
                    saveAddress(
                      id: address?['id'],
                      name: nameController.text,
                      phone: phoneController.text,
                      province: selectedProvince.value,
                      city: selectedCity.value,
                      district: selectedDistrict.value,
                      detailedAddress: detailedAddressController.text,
                      isDefault: isDefault.value,
                    );
                  },
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF67F41),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Text(
                      '保存地址',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: MediaQuery.of(Get.context!).viewInsets.bottom),
              ],
            ),
          ),
        ),
      ),
      isScrollControlled: true,
      isDismissible: true,
    );
  }

  /// 构建输入框
  Widget _buildInputField(String label, String hint, TextEditingController controller, {bool showLocationIcon = false}) {
    // 详细地址需要更多高度
    final isDetailedAddress = label == '详细地址';
    
    return Container(
      padding: EdgeInsets.only(bottom: 40.h),
      height: isDetailedAddress ? 120.h : null,
      
      child: Row(
        crossAxisAlignment: isDetailedAddress ? CrossAxisAlignment.start : CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 80.w,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ),
          Expanded(
            child: TextField(
              controller: controller,
              maxLines: isDetailedAddress ? 3 : 1,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
              ),
              decoration: InputDecoration(
                hintText: hint,
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xffD9D9D9),
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
                isDense: true,
              ),
            ),
          ),
          if (showLocationIcon)
            Padding(
              padding: EdgeInsets.only(top: isDetailedAddress ? 0 : 0),
              child: Assets.points.location.image(width:24.w,height:24.h)
            ),
        ],
      ),
    );
  }

  /// 构建选择框
  Widget _buildSelectField(String label, String hint, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.only(bottom: 40.h),
        
        child: Row(
          children: [
            SizedBox(
              width: 80.w,
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                ),
              ),
            ),
            Expanded(
              child: Text(
                hint,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Color(0xffD9D9D9),
                ),
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey[500],
              size: 16.sp,
            ),
          ],
        ),
      ),
    );
  }
}
